package com.it.demo010;

public class MyRunnable implements  Runnable{
    private static int tickeCount =100;
    @Override
    public void run() {
        while (true){
            if("窗口一".equals(Thread.currentThread().getName())){
                boolean result = synchronizedMthod();
                if(result){
                    break;
                }
            }
            if("窗口二".equals(Thread.currentThread().getName())){
                //同步代码块
                //对类对象加锁
                //单例模式
                synchronized(MyRunnable.class){
                    if(tickeCount == 0){
                        break;
                    }else {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        tickeCount--;
                        System.out.println(Thread.currentThread().getName()+"在卖票，还剩下"+tickeCount+"张票");
                    }
                }
            }
        }
    }
    //同步方法
    private static synchronized boolean synchronizedMthod() {
        if(tickeCount == 0){
            return true;
        }else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tickeCount--;
            System.out.println(Thread.currentThread().getName()+"在卖票，还剩下"+tickeCount+"张票");
            return false;
        }
    }
}
